import logging
import math
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
# from fastapi import Request
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

check_type_router = APIRouter(prefix="/inspection/type", tags=["巡查类型管理"], dependencies=[Depends(oauth2_scheme)])


class CheckTypeSearch(PaginationBase):
    fcheckname: str = Field("", description="巡查类型名称")


@check_type_router.get("/list", summary="巡查类型查询接口")
def list_check_type(search: CheckTypeSearch = Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from s_ts_check_type where 1=1"
    if search.fcheckname != "":
        sql = sql + " and fcheckname like concat('%', :fcheckname ,'%') "
        param["fcheckname"] = search.fcheckname
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select fchecktypeno,fcheckname,fmemo,fupddate,foperator"
    sql = sql + " from s_ts_check_type where 1=1"
    if search.fcheckname != "":
        sql = sql + " and fcheckname like concat('%', :fcheckname ,'%') "
        param["fcheckname"] = search.fcheckname
    if search.order == "desc":
        sql = sql + " order by  fchecktypeno desc "
    else:
        sql = sql + " order by  fchecktypeno "
    sql = sql + " limit :limit offset :offset "
    param["limit"] = search.limit
    param["offset"] = search.offset
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['fchecktypeno'] = data[key][0]
        d1['fcheckname'] = data[key][1]
        d1['fmemo'] = data[key][2]
        d1['fupddate'] = data[key][3]
        d1['foperator'] = data[key][4]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": search.limit,
                 "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)


class CheckTypeCreate(BaseModel):
    """巡查类型新增请求参数"""
    fchecktypeno: str = Field(..., description="巡查类型编号（唯一标识）")
    fcheckname: str = Field(..., description="巡查类型名称")
    foperator: str = Field(..., description="操作人")
    fupddate: str = Field(..., description="更新日期(yyyy-MM-dd HH:mm:ss)")
    fmemo: Optional[str] = Field("", description="备注")


@check_type_router.post("/create", summary="巡查类型新增接口")
def create_check_type(create: CheckTypeCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select fchecktypeno from s_ts_check_type where fchecktypeno= :fchecktypeno "
            data = db.execute(text(sql), {"fchecktypeno": create.fchecktypeno}).fetchall()

            if len(data) > 0:
                return BaseResponse.error(message="编号已存在")
            else:
                sql = "insert into s_ts_check_type(fchecktypeno,fcheckname,fmemo,fupddate,foperator)"
                sql = sql + " values( :fchecktypeno , ：fcheckname , ：fmemo , ：fupddate , ：foperator );"
                db.execute(text(sql), {
                    "fchecktypeno": create.fchecktypeno,
                    "fcheckname": create.fcheckname,
                    "fmemo": create.fmemo,
                    "fupddate": create.fupddate,
                    "foperator": create.foperator
                })
                # 返回
                data = {"fchecktypeno": create.fchecktypeno
                    , "fcheckname": create.fcheckname
                    , "fmemo": create.fmemo
                    , "fupddate": create.fupddate
                    , "foperator": create.foperator
                        }
                return BaseResponse.success(data=data)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="未知错误")


@check_type_router.post("/update", summary="巡查类修改接口")
def update_check_type(update: CheckTypeCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "update s_ts_check_type"
            sql = sql + " set fcheckname= :fcheckname ,fmemo= :fmemo "
            sql = sql + ",fupddate= :fupddate ,foperator= :foperator "
            sql = sql + " where fchecktypeno= :fchecktypeno "
            db.execute(text(sql), {
                "fcheckname": update.fcheckname,
                "fmemo": update.fmemo,
                "fupddate": update.fupddate,
                "foperator": update.foperator,
                "fchecktypeno": update.fchecktypeno
            })
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="未知错误")


@check_type_router.post("/delete/{fchecktypeno}", summary="巡查类型删除接口")
def delete_check_type(fchecktypeno: str = Path(description="巡查类型编号"), db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "delete from s_ts_check_type where fchecktypeno= ：fchecktypeno "
            db.execute(text(sql), {"fchecktypeno": fchecktypeno})
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="未知错误")
